package com.antler.smt.validate;

import com.antler.smt.exception.ParamValidateException;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 数据校验
 *
 * @author vic
 * @date 2018-4-3 11:28
 */
public class DataValidator {

    /**
     * 判断参数是否为空或空字符串
     *
     * @param str     参数名称
     * @param message 错误信息
     */
    public static void isBlank(String str, String message) {
        if (StringUtils.isEmpty(str)) {
            throw new ParamValidateException(str, message);
        }
    }

    /**
     * 判断对象是否为空
     *
     * @param object  对象
     * @param message 错误信息
     */
    public static void isNull(Object object, String message) {
        if (object == null) {
            throw new ParamValidateException(null, message);
        }
    }

    /**
     * 判断枚举是否有效
     *
     * @param enumClass 枚举类
     * @param value     值
     * @param message   错误信息
     */
    public static void isInvalidEnumValue(Class enumClass, Integer value, String message) {
        if (enumClass.isEnum()) {
            Object[] enumConstants = enumClass.getEnumConstants();
            Object constant = enumConstants[0];
            try {
                //values method
                Method method = constant.getClass().getDeclaredMethod("values");
                Object[] resultArray = (Object[]) method.invoke(constant);
                //enum instance
                for (Object result : resultArray) {
                    Field keyField = result.getClass().getDeclaredField("key");
                    Field descField = result.getClass().getDeclaredField("desc");
                    keyField.setAccessible(true);
                    descField.setAccessible(true);
                    Integer enumValue = keyField.getInt(result);
                    if (value.intValue() == enumValue.intValue()) {
                        return;
                    }
                }
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | NoSuchFieldException e) {
                e.printStackTrace();
                throw new ParamValidateException(value, message);
            }
        }
        throw new ParamValidateException(value, message);
    }
}
